<template>
	<view>
		<view class="content">
			<view v-if="dynamicForm.items.length" class="dynamicForm">
				<u--form labelPosition="left" :model="dynamicForm" ref="refForm">
					<u-form-item v-for="(item, index) in dynamicForm.items" :key="item.key">
						<view class="add-zone">
							<view class="click-zone">
								<image src="/static/home_icons/delete.png" class="pix" @click.stop="removeCard(item)">
								</image>
								<image src="/static/home_icons/add.png" class="pix" @click.stop="addForm"></image>
							</view>
							<u-picker :show="show" :columns="columns" keyName='faultName' @confirm="confirm"
								:title="pickerTitle" @cancel="cancelPicker" @change="changeHandler" :loading="loading">
							</u-picker>
							<u-datetime-picker :show="showDateTime" v-model="dateTime" mode="datetime"
								closeOnClickOverlay @confirm="confirmDateTime" :loading="loading"
								@cancel="cancelDateTime" :title="pickerDateTitle">
							</u-datetime-picker>
							<view class="add-form">
								<u-cell-group :border="false">
									<u-cell size="normal" title="问题类别" isLink :value="item.faultName"
										@click="showPicker(0,item)">
									</u-cell>
									<view size="normal" v-if="item.faultName">
										<checkbox-group @change="checkboxChange" class="checkbox-zone">
											<checkbox :customStyle="{marginBottom: '16px'}"
												v-for="(box, index) in item.checkboxList" :key="index"
												:value="box.faultName" class="checkbox-item" size='30' color="red"
												@click="checkboxClick(item)">
												{{box.faultName}}
											</checkbox>
										</checkbox-group>
									</view>
									<u-cell size="normal" title="问题部位">
										<view slot="value">
											<input type="text" style="text-align: right;" v-model="item.issueLocation"
												placeholder="请输入" />
										</view>
									</u-cell>
									<u-cell size="normal" title="问题处理人">
										<view slot="value">
											<input type="text" style="text-align: right;" v-model="item.handlerUserId"
												placeholder="请输入" />
										</view>
									</u-cell>
									<u-cell size="normal" title="发现时间" :value="item.discoveryTime"></u-cell>
									<u-cell size="normal" title="预计处理时间" :value="item.estimatedProcessingTime" isLink
										@click="showPicker(1,item)">
									</u-cell>
									<u-cell size="normal" title="问题描述" :border="false" :value="item.input_num +'/200'"></u-cell>
									<view class="pixs">
										<textarea class="_textarea" maxlength="200" @input="monitorInput(item)"
											v-model="item.issuesDesc" placeholder="请描述问题，最多输入200个字" />
										<!-- <span class="numLimit">{{item.input_num}}/200</span> -->
									</view>
									<u-cell size="normal" title="现场情况" :border="false"></u-cell>
									<view class="pixs">
										<u-upload :fileList="item.fileList" @afterRead="afterRead" name="pix"
											:maxCount="9" width="188rpx" height="188rpx" :previewFullImage="true"
											multiple @delete="deletePic" :itemData="item">
										</u-upload>
									</view>
								</u-cell-group>
							</view>
						</view>
					</u-form-item>
				</u--form>
			</view>
			<view v-else>
				<view class="add-zone">
					<view class="click-zone">
						<image src="/static/home_icons/delete.png" class="pix" @click.stop=""></image>
						<image src="/static/home_icons/add.png" class="pix" @click.stop="addForm()"></image>
					</view>
				</view>
				<u-empty text="暂无记录~" icon="/static/home_icons/nodata.png" marginTop="166rpx" width="200rpx"
					height="131rpx">
				</u-empty>
			</view>
			<view class="btns">
				<button type="default" class="last" @click="returnLeft()">上一页</button>
				<button type="default" class="last" @click="save()">暂存</button>
				<button type="default" class="next" @click="push()">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import _public from "@/common/public.js"
	import _file from "@/common/file.js"
	export default {
		props: {
			nextUrl: String,
			node: Object
		},
		name: "StepThree",
		data() {
			return {
				// u-checkbox-group的v-model绑定的值如果设置为某个checkbox的name，就会被默认选中
				checkboxValue: [],
				loading: false,
				pickerDateTitle: '',
				showDateTime: false,
				dateTime: Number(new Date()),
				dynamicForm: {
					items: []
				},
				progressData: [],
				fileIds: [],
				flag: 0,
				formList: [],
				fileList: [],
				columns: [],
				columnData: [],
				pickerTitle: '',
				showEmpty: true,
				title: "",
				show: false,
				temp: 0,
				safeForm: [],
			};
		},
		created() {
			this.getProgressList()
			this.init()
		},
		methods: {
			monitorInput(item) {
				this.dynamicForm.items[this.temp].input_num = item.issuesDesc.length
			},
			checkboxClick(item) {
				this.checkboxChange(item)
			},
			checkboxChange: function(e) {
				console.log(e)
				if (typeof e.type != 'undefined' && e.type == 'change') {
					this.checkboxValue = e.detail.value
				} else {
					console.log(this.checkboxValue)
					let index = this.dynamicForm.items.indexOf(e)
					this.dynamicForm.items[index].issueTags = this.checkboxValue.toString()
				}
			},
			async init() {
				let _i = await _public.getSafeData()
				// let all = _public.getChildData()
				let _j = await _public.getChildData()
				let _k = []
				_k.push(_i)
				_k.push(_j[0])
				this.columns = _k
				this.columnData = _j
			},
			returnLeft() {
				this.$emit('returnLast')
			},
			removeCard(data) {
				let index = this.dynamicForm.items.indexOf(data)
				if (index !== -1) {
					this.dynamicForm.items.splice(index, 1)
				}
			},
			addForm() {
				this.dynamicForm.items.push({
					key: Date.now(),
					estateId: this.node.estateId,
					issueStatus: 1,
					issuesType: 2,
					partId: this.node.partId,
					fileList: [],
					discoveryTime: uni.$u.timeFormat(false, 'yyyy-mm-dd'),
					issueTags: [],
					faultId: "",
					issueImages: "",
					issueLocation: '',
					issuesStatus: 1,
					projectName: "",
					estimatedProcessingTime: '',
					handlerUserId: '',
					issuesDesc: '',
					partName: '',
					flag: this.node.flag,
					input_num: 0
					
				})
			},
			formatData() {
				//数据校验
				let flag = true
				let _form_data = this.dynamicForm.items
				for (let i = 0; i < _form_data.length; i++) {
					let j = i + 1
					if (_form_data[i].faultId == '') {
						uni.$showMsg('第' + j + '组尚未选择问题类别')
						flag = false
						break
					} else if (_form_data[i].issueLocation == '') {
						uni.$showMsg('第' + j + '组尚未输入问题部位')
						flag = false
						break
					} else if (_form_data[i].estimatedProcessingTime == '') {
						uni.$showMsg('第' + j + '组尚未上选择预处理时间')
						flag = false
						break
					} else if (_form_data[i].handlerUserId == '') {
						uni.$showMsg('第' + j + '组尚未上输入问题处理人')
						flag = false
						break
					} else if (_form_data[i].issuesDesc == '') {
						uni.$showMsg('第' + j + '组尚未描述问题')
						flag = false
						break
					} else if (_form_data[i].fileList == '') {
						uni.$showMsg('第' + j + '组尚未上传现场图片')
						flag = false
						break
					}
				}
				//校验数据
				if (flag) {
					let cloneData = uni.$u.deepClone(this.dynamicForm.items)
					for (let i = 0; i < cloneData.length; i++) {
						let pixs = []
						for (let j = 0; j < cloneData[i].fileList.length; j++) {
							pixs.push(cloneData[i].fileList[j].urlId)
						}
						cloneData[i].issueImages = pixs.toString()
					}
					this.safeForm = cloneData
					//是否立即上传
					this.$emit('saveData', cloneData)
					return flag
				}
			},
			//暂存提交
			save() {
				if (this.formatData()) {
					this.$emit('goToNext', 'save')
				}
			},
			//直接提交
			push() {
				if (this.formatData()) {
					this.$emit('goToNext', 'push')
				}
			},
			// 删除图片
			deletePic(event) {
				let i = this.dynamicForm.items.indexOf(event.itemData)
				this.dynamicForm.items[i].fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let index = this.dynamicForm.items.indexOf(event.itemData)
				let lists = [].concat(event.file)
				let fileListLen = this.dynamicForm.items[index].fileList.length
				lists.map((item) => {
					this.dynamicForm.items[index].fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _file.uploadFilePromise(lists[i].url)
					const temp = JSON.parse(result)
					let item = this.dynamicForm.items[index].fileList[fileListLen]
					this.dynamicForm.items[index].fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						urlId: temp.body.fileId
					}))
					fileListLen++
				}
			},
			confirmDateTime(time) {
				this.dynamicForm.items[this.temp].estimatedProcessingTime = uni.$u.timeFormat(time.value,
					'yyyy-mm-dd hh:MM')
				this.showDateTime = false
			},
			cancelPicker() {
				this.show = false
			},
			cancelDateTime() {
				this.showDateTime = false
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					picker
				} = e
				if (columnIndex === 0) {
					this.loading = true
					// 模拟网络请求
					uni.$u.sleep(500).then(() => {
						picker.setColumnValues(1, this.columnData[index])
						this.loading = false
					})
				}
			},
			//待测试
			async confirm(item) {
				console.log(item)
				switch (this.flag) {
					case 0:
						if (typeof item.value[1] == undefined) {
							this.dynamicForm.items[this.temp].faultName = item.value[0].faultName
							this.dynamicForm.items[this.temp].faultId = item.value[0].faultId
						} else {
							this.dynamicForm.items[this.temp].faultName = item.value[0].faultName + '-' + item.value[1]
								.faultName
							// if()
							this.dynamicForm.items[this.temp].faultId = item.value[1].faultId
							this.dynamicForm.items[this.temp].checkboxList = await _public.getchild(item.value[1]
								.faultId)
							console.log(this.checkboxList)
						}

						break;
				}
				this.show = false
			},
			//获取进度列表
			async getProgressList() {
				const {
					data
				} = await uni.$http.get(uni.$http.baseURL + '/constant/getByType', {
					type: 1
				})
				if (data.message == '成功') {
					let list = data.body
					for (let i = 0; i < list.length; i++) {
						this.progressData.push(list[i].constantValue)
					}
				}
			},
			showPicker(item, data) {
				let index = this.dynamicForm.items.indexOf(data)
				this.flag = item
				this.temp = index
				switch (this.flag) {
					case 0:
						this.pickerTitle = '安全问题类别'
						// this.columns = [this.progressData]
						this.show = true
						break;
					case 1:
						this.pickerDateTitle = '预计处理时间'
						this.showDateTime = true
						break;
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.content {
		display: block;
		padding: 20rpx 30rpx 58rpx 30rpx;

		.process-bar {
			display: block;
			border: 1rpx solid #efefef;
			border-radius: 20rpx;
			background-color: #FFFFFF;
			padding: 30rpx;
			margin-bottom: 20rpx;

			.steps {
				margin-top: 45rpx;
			}
		}

		.dynamicForm {
			display: block;

			.add-zone {
				width: 100%;
			}
		}


	}

	.add-zone {
		padding: 20rpx;
		border: 1rpx solid #efefef;
		border-radius: 20rpx;
		background-color: #FFFFFF;
	}

	.add-form {
		display: flex;
		flex-direction: column;

		.pixs {
			padding: 20rpx;

		}
	}

	.click-zone {
		display: flex;
		flex-direction: row;
		justify-content: space-between;

		.pix {
			width: 40rpx;
			height: 40rpx;
		}
	}

	.btns {
		margin-top: 88rpx;
		display: flex;
		flex-direction: column;

		.last {
			color: #E62029;
			width: 580rpx;
			background: #FFFFFF;
			border: 2rpx solid #E62029;
			border-radius: 44rpx;
			margin-bottom: 40rpx;
		}

		.next {

			width: 580rpx;
			background: linear-gradient(90deg, #E62129 0%, #BA000A 100%);
			box-shadow: 0rpx 5rpx 15rpx 0rpx rgba(0, 0, 0, 0.05);
			border-radius: 44rpx;
			color: #FFFFFF;
		}
	}

	.checkbox-zone {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		padding: 20rpx 30rpx;
		// text-align: center;

		.checkbox-item {
			margin-top: 10rpx;
			width: 50%;
		}
	}
	._textarea {
		// width: 620rpx;
		height: 160rpx;
		background: #F5F5F5;
		border-radius: 10rpx;
	}
	
	.numLimit {
		position: relative;
		top: -40rpx;
		right: -530rpx;
	
	}
</style>
